package com.yt.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.yt.common.Constants;
import com.yt.dao.AuthorMapper;
import com.yt.exception.AuthorException;
import com.yt.pojo.Author;
import com.yt.pojo.ReturnResult;
import com.yt.pojo.ReturnResultUtils;
import com.yt.service.AuthorService;
import com.yt.util.EmptyUtils;
import com.yt.util.RedisUtil;
import com.yt.util.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class AuthorServiceImpl implements AuthorService {
    @Resource
    AuthorMapper authorMapper;

    @Resource
    RedisUtil redisUtil;
    @Override
    public List<Author> getAllAuthors() {
        return authorMapper.selectAll();
    }

    @Override
    public ReturnResult<Author> getAllAuthorByName(String name) {

        ReturnResult returnResult=null;
        Author author=new Author();
        author.setAuthor(name);
        String token=null;
        List<Author> authors=authorMapper.select(author);
        if(authors.size()==0){
          return  ReturnResultUtils.returnFail(404,"作者不存在");
        }
        author= authors.get(0);
        log.info(author.toString());
        if(null!=author){
            //如果验证成功，生成token放在redis
            String oldToken=redisUtil.getStr(author.getId()+"");
            if(EmptyUtils.isNotEmpty(oldToken)){
                redisUtil.del(oldToken);
                redisUtil.del(author.getId()+"");
            }//session更新时间，30分
            token= Constants.tokenPrefix+ TokenUtils.createToken(author.getId()+"",author.getAuthor());
            redisUtil.setStr(token, JSONObject.toJSONString(author), Constants.loginExpire);
            redisUtil.setStr(author.getId()+"", token,Constants.loginExpire);
            Map<String,Object> result=new HashMap<String,Object>();
            result.put("token",token);
            returnResult= ReturnResultUtils.returnSuccess(result);
        }else{
            returnResult= ReturnResultUtils.returnFail(AuthorException.USER_PASSWORD_ERROR.getCode(),AuthorException.USER_PASSWORD_ERROR.getMessage());
        }
        return returnResult;
    }

    @Override
    public ReturnResult<List<Author>> getAllAuthors(String token) {
        if(token==null || token.equals(""))
            return  ReturnResultUtils.returnFail(
                    404,"需要登录");

        String authorJson=redisUtil.getStr(token);
        Author author= JSONObject.parseObject(authorJson,Author.class);
        log.info(author.toString());
        return ReturnResultUtils.returnSuccess(authorMapper.selectAll());
    }
}
